<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
       <!-- <el-form-item prop="deptId">
          <treeselect v-model="queryParams.deptId" :options="deptOptions" :show-count="true" placeholder="部门"
            style="width: 480px" />
        </el-form-item> -->
        <el-form-item prop="storeId">
          <!-- <treeselect v-model="queryParams.storeId" :options="storeOptions" :show-count="true" placeholder="请选择仓库"
            style="width: 480px" size="mini"/> -->
            <el-select v-model="queryParams.storeId" placeholder="仓库" clearable size="small">
                <el-option v-for="dict in storeOptions" :key="dict.id" :label="dict.label"
                  :value="dict.id" />
              </el-select>
        </el-form-item>

        <el-form-item prop="pickNo">
          <el-input v-model="queryParams.pickNo" placeholder="挑拣编号" clearable
            @keyup.enter.native="handleQuery" size="small"/>
        </el-form-item>
        <el-form-item prop="proKey">
          <el-input v-model="queryParams.proKey" placeholder="物品编号/名称/特征关键字搜索" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item prop="operator">
          <el-select v-model="queryParams.operator" placeholder="挑拣员" size="small">
            <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item prop="status">
          <el-select v-model="queryParams.status" placeholder="状态" clearable>
            <el-option v-for="dict in dict.type.wms_pick_task_status" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item> -->

        <el-form-item>
          <el-date-picker v-model="daterangeFinishTime"  style="width: 240px" value-format="yyyy-MM-dd" size="small"
            type="daterange" range-separator="-" start-placeholder="挑拣起始日期" end-placeholder="截止日期"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row>
        <el-col :span="16" class="mb10">
          <el-radio-group v-model="queryParams.status" @change="radioChange">
            <el-radio-button v-for="tab in tabs" :label="tab.label" >
              <el-badge :value="tab.badge" class="item">
                {{tab.name}}
              </el-badge>
            </el-radio-button>
          </el-radio-group>
        </el-col>
      </el-row>

      <!-- <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['wms:pick:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
            v-hasPermi="['wms:pick:edit']">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['wms:pick:remove']">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
            v-hasPermi="['wms:pick:export']">导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row> -->

      <el-table v-loading="loading" :data="pickList" @selection-change="handleSelectionChange" border stripe>
        <el-table-column type="index" width="55" align="center" />
        <el-table-column label="挑拣编号" align="center" prop="pickNo" min-width="100">
            <template slot-scope="scope">
              <el-link type="primary" @click="handleInfo(scope.row)">{{scope.row.pickNo}}</el-link>
            </template>
        </el-table-column>
        <!-- <el-table-column label="物品编号" align="center" prop="proNo" min-width="100" /> -->
        <el-table-column label="仓库" align="center" prop="storeName" min-width="80" />
        <el-table-column label="库区" align="center" prop="areaName" min-width="80" />
        <!-- <el-table-column label="部门" align="center" prop="deptName" min-width="300"/> -->
        <el-table-column label="挑拣员" align="center" prop="nickName" />
        <el-table-column label="挑拣时间" align="center" prop="finishTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.finishTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请时间" align="center" prop="createTime">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
        <!-- <el-table-column label="描述" align="center" prop="memo" width="180" /> -->
        <el-table-column label="状态" align="center" prop="status" width="80">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.wms_pick_task_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['wms:pick:edit']">修改</el-button>
            <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['wms:pick:remove']">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    <!-- 添加或修改挑拣任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1280px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="出库单号" prop="wno">
              <el-input v-model="form.exno" placeholder="请输入出库单号" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务编号" prop="pickNo">
              <el-input v-model="form.pickNo" placeholder="请输入任务编号" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" @change="statusChange">
                <el-option v-for="dict in dict.type.wms_pick_task_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="部门" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="管理部门"
                style="width: 100%" size="small" />
            </el-form-item>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库" prop="storeId">
              <treeselect v-model="form.storeId" :options="storeOptions" :show-count="true"
                placeholder="请选择仓库" append-to-body  z-index="9999"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">

          <el-col :span="8">
            <el-form-item label="挑拣员" prop="operator">
              <el-select v-model="form.operator" placeholder="请选择挑拣员" style="width: 100%">
                <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName" :value="item.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="完成时间" prop="finishTime">
              <el-date-picker clearable size="small" v-model="form.finishTime" type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择完成时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label="备注" prop="memo">
              <el-input v-model="form.memo" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row class="mb20">
           <el-col :offset="2" :span="22">
            <el-card shadow="hover">
              <div slot="header" class="clearfix">
                <span>挑拣清单</span>
                <el-button type="text" style="float:right;padding: 3px 0" @click="addDtl">新增</el-button>
              </div>
              <el-table :data="form.items" border stripe>
                <el-table-column label="物品编号" align="center" prop="pno">
                  <template slot-scope="scope">
                    <el-input placeholder="请输入物品编号" v-model="scope.row.pno" />
                  </template>
                </el-table-column>
                <el-table-column label="物品名称" align="center" prop="name">
                  <template slot-scope="scope">
                    <el-input placeholder="请输入物品名称" v-model="scope.row.name" />
                  </template>
                </el-table-column>
                <el-table-column label="仓库" align="center" prop="storeId">
                  <template slot-scope="scope">
                    <treeselect v-model="scope.row.storeId" :options="storeOptions" :show-count="true"
                      placeholder="请选择仓库" style="width: 120px;" append-to-body  z-index="9999"/>
                  </template>
                </el-table-column>
               <el-table-column label="库区" align="center" prop="areaId">
                 <template slot-scope="scope">
                   <el-select v-model="scope.row.areaId" placeholder="请选择库区" style="width: 120px;">
                     <el-option
                       v-for="item in storeAreaOptions"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"
                       v-if="item.storeId == scope.row.storeId"
                     />
                   </el-select>
                 </template>
               </el-table-column>
               <el-table-column label="库位" align="center" prop="locatorId">
                 <template slot-scope="scope">
                   <el-select v-model="scope.row.locatorId" placeholder="请选择库位" style="width: 120px;">
                     <el-option
                       v-for="item in locatorOptions"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"
                       v-if="item.areaId == scope.row.areaId"
                     />
                   </el-select>
                 </template>
               </el-table-column>
               <el-table-column label="数量" align="center" prop="nums">
                 <template slot-scope="scope">
                  <el-input placeholder="请输入物品数量" v-model="scope.row.nums" />
                 </template>
               </el-table-column>
               <el-table-column label="状态" align="center" prop="deptId">
                 <template slot-scope="scope">
                   <el-select v-model="scope.row.status" placeholder="请选择状态">
                     <el-option
                       v-for="dict in dict.type.wms_pick_task_status"
                       :key="dict.value"
                       :label="dict.label"
                       :value="dict.value"
                     ></el-option>
                   </el-select>
                 </template>
               </el-table-column>
                <el-table-column label="操作" align="left">
                  <template slot-scope="scope">
                    <el-row>
                      <el-col>
                        <el-button type="danger" size="mini" @click="dtlDel(scope)" v-if="scope.row.delFlag == '0'">删除
                        </el-button>
                        <el-tag type="info" v-if="scope.row.delFlag == '2'">已删除</el-tag>
                      </el-col>
                    </el-row>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label="图片附件" prop="pics">
              <image-upload v-model="form.pics" ref="imageUpload" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="接收人" prop="acceptUser">
              <el-input v-model="form.acceptUser" placeholder="请输入接收人" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="接收状态" prop="acceptStatus">
              <el-select v-model="form.acceptStatus" placeholder="请选择接收状态">
                <el-option v-for="dict in dict.type.wms_accept_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="接收时间" prop="acceptTime">
              <el-date-picker clearable size="small" v-model="form.acceptTime" type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择接收时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <selectProperty  ref="elDrawer" @handleSelected="handleSelected"></selectProperty>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listPick,
    getPick,
    delPick,
    addPick,
    updatePick,
    initBean
  } from "@/api/wms/pick";
  import {
    listStore,
    storeTreeselect
  } from "@/api/wms/store";
  import {
    storeAreas
  } from "@/api/wms/storeArea";
  import {
    locatores
  } from "@/api/wms/locator";
  import {
    treeselect
  } from "@/api/system/dept";
  import {
    listUser
  } from "@/api/system/user"
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import selectProperty from "@/components/SelectProperty/index.vue";
  export default {
    name: "Pick",
    dicts: ['sys_del_flag', 'wms_accept_status', 'wms_pick_task_status'],
    components: {
      Treeselect,
      selectProperty
    },
    data() {
      return {
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 挑拣任务表格数据
        pickList: [],
        storeOptions: [],
        userOptions: [],
        storeTree: [],
        storeName: undefined,
        deptOptions: [],
        storeAreaOptions: [],
        storeAreas: [],
        locatorOptions: [],
        locators: [],
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 接收状态时间范围
        daterangeFinishTime: [],
        // 接收状态时间范围
        daterangeCreateTime: [],
        // 接收状态时间范围
        daterangeAcceptTime: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          wid: undefined,
          storeId: undefined,
          deptId: undefined,
          pickNo: undefined,
          status: undefined,
          operator: undefined,
          finishTime: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          acceptUser: undefined,
          acceptTime: undefined,
          acceptStatus: undefined,
          delFlag: "0",
          proKey:undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          operator:[{
            required: true,
            message: "挑拣员不能为空",
            trigger: "change"
          }]
        },
        tabs:[
          {label:undefined,name:'全部',badge:undefined,value:undefined},
          {label:'0',name:'待挑拣',badge:undefined,value:'0'},
          {label:'1',name:'已挑拣',badge:undefined,value:'1'}
        ],
      };
    },
    watch: {
      storeName(val) {
        this.$refs.tree.filter(val);
      },
      'queryParams.deptId': {
        handler(newVal, oldVal) {
          this.deptChange();
        }
      }
    },
    created() {
      this.getList();
      this.getStoreTreeselect();
      this.getTreeselect();
      this.getUsers();
      this.getAreaAndLocators();
    },
    methods: {
      /** 查询挑拣任务列表 */
      getList() {
        this.loading = true;
        this.queryParams.params = {};
        if (null != this.daterangeFinishTime && '' != this.daterangeFinishTime) {
          this.queryParams.params["beginFinishTime"] = this.daterangeFinishTime[0];
          this.queryParams.params["endFinishTime"] = this.daterangeFinishTime[1];
        }
        if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
          this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
          this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
        }
        if (null != this.daterangeAcceptTime && '' != this.daterangeAcceptTime) {
          this.queryParams.params["beginAcceptTime"] = this.daterangeAcceptTime[0];
          this.queryParams.params["endAcceptTime"] = this.daterangeAcceptTime[1];
        }
        listPick(this.queryParams).then(response => {
          this.pickList = response.rows;
          this.total = response.total;
          this.loading = false;

          this.tabs.forEach((item)=>{
          	if(item.label == this.queryParams.status){
          		item.badge = this.total;
          	}else{
          		item.badge = undefined;
          	}
          })
        });
      },
      radioChange(e){
        this.tabs.forEach(item=>{
            if(item.label == e){
              this.queryParams.status = item.value;
            }
        })
        this.getList();
      },
      /** 查询分类下拉树结构 */
      getStoreTreeselect() {
        storeTreeselect().then(response => {
          this.storeOptions = response.data;
        });
      },
      getAreaAndLocators() {
        storeAreas({
          "storeId": this.queryParams.storeId
        }).then(response => {
          this.storeAreaOptions = response.data;
        });
        locatores({
          "storeId": this.queryParams.storeId
        }).then(response => {
          this.locatorOptions = response.data;
        });
      },
      /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
      getUsers() {
        listUser({
          'userType': 'sys_user',
          'deptId': this.queryParams.deptId,
          'postCode':'Picker,PutTasker'
        }).then(response => {
          this.userOptions = response.rows
        })
      },
      deptChange() {
        this.getUsers()
        this.getList();
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.storeId = data.id;
        this.handleQuery();
        this.getAreaAndLocators()
      },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      statusChange(e){
        this.form.items.forEach(item => {
          item.status = e;
        })
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          wid: undefined,
          storeId: undefined,
          deptId: undefined,
          pickNo: undefined,
          status: undefined,
          memo: undefined,
          pics: undefined,
          operator: undefined,
          finishTime: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          acceptUser: undefined,
          acceptTime: undefined,
          acceptStatus: undefined,
          delFlag: undefined,
          items: []
        };
        this.resetForm("form");
      },
      addDtl() {
        // let data = {
        //   id: undefined,
        //   taskId: undefined,
        //   pno: undefined,
        //   name: undefined,
        //   storeId: this.form.storeId,
        //   areaId: undefined,
        //   locatorId: undefined,
        //   status: '0',
        //   pics: undefined,
        //   operator: this.form.operator,
        //   putTime: undefined,
        //   memo: undefined,
        //   delFlag: '0'
        // }
        // this.form.items.push(data)
        this.$refs.elDrawer.open()
      },
      dtlDel(scope) {
        let index = scope.$index;
        if (this.form.items[index].id && this.form.items[index].id != '') {
          this.form.items[index].delFlag = '2';
        } else {
          this.form.items.splice(index, 1)
        }
      },
      handleInfo(row){
        this.$router.push({
          path: '/wms/pickInfo/info/'+row.id,
          query: {
            pageNum: this.queryParams.pageNum
          }
        })
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.daterangeFinishTime = [];
        this.daterangeCreateTime = [];
        this.daterangeAcceptTime = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        // this.reset();
        // this.open = true;
        // this.title = "添加挑拣任务";
        // this.form.storeId = this.queryParams.storeId;
        // this.getAreaAndLocators();
        // this.$refs.elDrawer.getList()
        this.$router.push({
          path: '/wms/pickInfo/add',
          query: {
            pageNum: this.queryParams.pageNum
          }
        })
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        // this.loading = true;
        // this.reset();
        // this.getAreaAndLocators();
        // const id = row.id || this.ids
        // getPick(id).then(response => {
        //   this.loading = false;
        //   this.form = response.data;
        //   this.open = true;
        //   this.title = "修改挑拣任务";
        // });
        // this.$refs.elDrawer.getList()
        const id = row.id || this.ids
        this.$router.push({
          path: '/wms/pickInfo/edit/'+id,
          query: {
            pageNum: this.queryParams.pageNum
          }
        })
      },
      //获取选择后的财务数据
        handleSelected(array){
          array.forEach(item=>{
            item.delFlag = '0'
            item.id=undefined
            item.status=this.form.status
            item.operator=this.form.operator
            this.form.items.push(item)
          })
        },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          this.form.oss = this.$refs["imageUpload"].pics;
          if (valid) {
            this.buttonLoading = true;
            if (this.form.id != null) {
              updatePick(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addPick(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除挑拣任务编号为"' + ids + '"的数据项？').then(() => {
          this.loading = true;
          return delPick(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).finally(() => {
          this.loading = false;
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('wms/pick/export', {
          ...this.queryParams
        }, `pick_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
